var gulp = require('gulp'),
    gutil = require('gulp-util'),
    plumber = require('gulp-plumber'),
    rename = require('gulp-rename'),
    rev = require('gulp-rev'),
    chalk = require('chalk');

var webpack = require('webpack');

var sass = require('gulp-sass'),
    minify = require('gulp-minify-css'),
    autoprefixer = require('gulp-autoprefixer');

var browserSync = require('browser-sync').create();

gulp.task('develop', ['html', 'es6', 'sass'], function() {
    browserSync.init({
        logFileChanges: false,
        server: {
            baseDir: './'
        }
    });
    gulp.watch('index.html', ['html']);
    gulp.watch('src/sass/**/*.sass', ['sass']);
    gulp.watch('src/script/**/*.js', ['es6', 'html']);
    gulp.watch(['index.html',
                'src/sass/**/*.sass',
                'src/script/**/*.js'])
      .on('change', function(event) {
        console.log('File \'' + chalk.yellow(event.path.replace(__dirname, ''))
          + '\' was [' + chalk.magenta( event.type ) + '], runing tasks...');
    });
});

gulp.task('html', function() {
    return gulp.src('index.html')
        .pipe(browserSync.stream());
});

gulp.task('es6', function(callback) {
  webpack({
    entry: {
      app: './src/script/app.js'
    },
    output: {
      path: './dist/script',
      filename: '[name].bundle.js'
    },
    resolve: {
      extensions: [ '', '.js' ]
    },
    module: {
      loaders: [
        {
          test: /\.js$/,
          loader: 'babel',
          exclude: /node_modules/
        }
      ],
    },
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        },
        output: {
          comments: false
        }
      })
    ]
  }, function(err, stats) {
    if (err) throw new gutil.PulginError('webpack', err);
    gutil.log('[webpack]', stats.toString());
    callback();
  });
});

gulp.task('sass', function() {
  return gulp.src('src/sass/import.sass')
    .pipe(plumber())
    .pipe(sass())
    .pipe(rename('app.css'))
    // .pipe(gulp.dest('dist/css')) // export app.css
    .pipe(minify({ compatibility: 'ie7', keepSpecialComments: 0 }))
    .pipe(autoprefixer({ browsers: ['> 1%', 'IE 7'], cascade: false }))
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest('dist/css')) // export app.min.css
    .pipe(browserSync.stream());
});

gulp.task('default', ['develop']);